using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Tracker.Mobile.Droid.TrackerWebService;
using System.Threading;

namespace Tracker.Mobile.Droid.Activities
{
    [Activity(Label = "My Activity")]
    public class Register : BaseActivity
    {
        private EditText _username;
        private EditText _email;
        private EditText _password;
        private EditText _confirmPassword;
        private Button _register;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Register);
            Initialize();   
        }

        private void Initialize()
        {
            _username = FindViewById<EditText>(Resource.Id.RegisterUsername);
            _email = FindViewById<EditText>(Resource.Id.RegisterEmail);
            _password = FindViewById<EditText>(Resource.Id.RegisterPassword);
            _confirmPassword = FindViewById<EditText>(Resource.Id.RegisterConfirmPassword);
            _register = FindViewById<Button>(Resource.Id.Register);
            _register.Click += (sender, args) =>
            {
                var dto = new UserDTO();
                dto.Username = _username.Text;
                dto.Email = _email.Text;
                dto.Password = _password.Text;

                if (dto.Password != _confirmPassword.Text)
                {
                    Toast.MakeText(this, "The passwords are not the same", ToastLength.Long).Show();
                    return;
                }

                ProgressDialog dialog = Util.CreateProgressDialog(this, ProgressDialogStyle.Spinner, "Please Wait", "Creating your account");

                ThreadPool.QueueUserWorkItem(state =>
                {
                    dto = WebService.Register(dto);

                    if (dto.ID > 0)
                    {
                        UserID = dto.ID;
                        Username = dto.Username;
                        Email = dto.Email;

                        Intent home = new Intent(this, typeof(Home));
                        StartActivity(home);
                    }
                    else
                    {
                        RunOnUiThread(() =>
                        {
                            Toast.MakeText(this, "An error occurred while creating your account", ToastLength.Long).Show();
                        });
                    }
                });
            };
        }
    }
}